package com.kgd.news.controller.admin;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.kgd.news.entity.SysUser;
import com.kgd.news.utils.Api;
import com.kgd.news.utils.BaseController;
import com.kgd.news.utils.DateUtils;

/**
 * @Email: huangsanm@foxmail.com
 * @Date: 2017/6/2
 * @Time: 下午5:46
 */
public class UserController extends BaseController {

    public void login() {
        String account = getPara("account");
        SysUser user = SysUser.dao.findFirst("select * from sys_user where account = ? ", account);
        if (user == null) {
            renderJson(new Api(Api.D_204, "用户不存在").get());
            return;
        }
        // 1正常使用,2冻结
        if (user.getStatus() != null && user.getStatus() == 2) {
            renderJson(new Api(Api.D_204, "该用户已被冻结，请联系管理员").get());
            return;
        }

        //验证密码
        String pwd = getPara("password");
        if (!pwd.equals(user.getPasswd())) {
            renderJson(new Api(Api.D_204, "密码错误，请重新输入").get());
            return;
        }

        //登录成功把用户信息缓存到session,是呀服务器就要存到settiogn里面
        cacheUser(user);
        renderJson(new Api("登录成功").get());
    }

    @Override
    public void list() {
        String sql = "from sys_user where 1 = 1  order by createtime desc";

        Page<SysUser> data = SysUser.dao.paginate(getPageIndex("user"), PAGE_SIZE, "select *", sql);
        setAttr("data", data);
        render("user_list.html");
    }

    @Override
    public void edit() {
        Integer id = getParaToInt("id");
        SysUser user = SysUser.dao.findById(id);
        setAttr("user", user);
        render("user_edit.html");
    }

    @Override
    public void save() {
        SysUser us = getModel(SysUser.class, "user");
        if (us != null && us.getId() != null) {
            us.update();
        } else {
            us.setCreatetime(DateUtils.getCurDate());
            us.save();
        }
        list();
    }

    @Override
    public void del() {
        String ids = getPara("ids");
        Db.update("delete from sys_user where id in (" + ids + ")");

        list();
    }
}
